<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="诉求类型" prop="demandsType">
        <el-select v-model="queryParams.demandsType" placeholder="请选择诉求类型" clearable style="width: 240px">
          <el-option label="问题咨询" value="问题咨询" />
          <el-option label="困难求助" value="困难求助" />
          <el-option label="投诉举报" value="投诉举报" />
          <el-option label="服务评价" value="服务评价" />
        </el-select>
      </el-form-item>
      <el-form-item label="诉求状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择诉求状态" clearable style="width: 240px">
          <el-option label="审核不通过" :value="-1" />
          <el-option label="待审核" :value="0" />
          <el-option label="待处理" :value="1" />
          <el-option label="已完成" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['claim:list:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['claim:list:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['claim:list:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['claim:list:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row> -->

    <el-table v-loading="loading" :data="claimList" >
      <!-- @selection-change="handleSelectionChange" -->
      <!-- <el-table-column type="selection" width="50" align="center" /> -->
      <!-- <el-table-column label="ID" align="center" key="id" prop="id" width="80" /> -->
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="诉求类型" align="center" key="demandsType" prop="demandsType" width="120" />
      <el-table-column label="企业名称" align="center" key="companyName" prop="companyName" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="标题" align="center" key="title" prop="title" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column label="内容" align="center" key="content" prop="content" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="诉求图片" align="center" key="images" width="120">
        <template slot-scope="scope">
          <div v-if="getImageList(scope.row.images).length > 0" style="display: inline-block; position: relative;">
            <el-image 
              :src="getImageList(scope.row.images)[0]" 
              :preview-src-list="getImageList(scope.row.images)" 
              style="width: 50px; height: 50px;" 
              fit="cover">
            </el-image>
            <span v-if="getImageList(scope.row.images).length > 1" style="position: absolute; bottom: -2px; right: -2px; background: rgba(0,0,0,0.6); color: white; font-size: 10px; padding: 1px 4px; border-radius: 2px;">
              {{ getImageList(scope.row.images).length }}
            </span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" key="contact" prop="contact" />
      <el-table-column label="联系电话" align="center" key="contactPhone" prop="contactPhone" />
      <el-table-column label="诉求状态" align="center" key="status" >
        <template slot-scope="scope">
          <el-tag :type="getAppealStatusType(scope.row.status)">
            {{ getAppealStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)" v-hasPermi="['claim:list:view']">受理详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size" @pagination="getList" />

    <!-- 添加或修改诉求配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业名称" prop="companyName">
              <el-input v-model="form.companyName" placeholder="请输入企业名称" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="内容" prop="content">
              <el-input v-model="form.content" type="textarea" placeholder="请输入内容" :rows="4" maxlength="500" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入联系人" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="诉求状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择处置状态">
                <el-option label="待处理" value="pending" />
                <el-option label="第一次确认结束" value="first_confirmed" />
                <el-option label="处理中" value="processing" />
                <el-option label="已完成" value="completed" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="诉求类型" prop="demandsType">
              <el-select v-model="form.demandsType" placeholder="请选择诉求类型">
                <el-option label="问题咨询" value="问题咨询" />
                <el-option label="困难求助" value="困难求助" />
                <el-option label="投诉举报" value="投诉举报" />
                <el-option label="服务评价" value="服务评价" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="诉求图片">
              <image-upload v-model="form.images" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 受理详情对话框 -->
    <el-dialog title="受理详情" :visible.sync="detailOpen" width="860px" append-to-body>
      <el-descriptions :column="2" border>
        <!-- <el-descriptions-item label="ID">{{ detailForm.id }}</el-descriptions-item> -->
        <el-descriptions-item label="标题">{{ detailForm.title }}</el-descriptions-item>
        <el-descriptions-item label="诉求类型">
          {{ detailForm.demandsType || '-' }}
        </el-descriptions-item>

        <el-descriptions-item label="企业名称">{{ detailForm.companyName }}</el-descriptions-item>
        <el-descriptions-item label="诉求状态">
          <el-tag :type="getAppealStatusType(detailForm.status)">
            {{ getAppealStatusText(detailForm.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="联系人">{{ detailForm.contact }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailForm.contactPhone }}</el-descriptions-item>

        <el-descriptions-item label="内容" :span="2">{{ detailForm.content }}</el-descriptions-item>
        <el-descriptions-item label="诉求图片" :span="2" >
          <div style="display: flex; flex-wrap: wrap; gap: 10px;" v-if="getImageList(detailForm.images).length > 0">
            <el-image 
              v-for="(img, index) in getImageList(detailForm.images)" 
              :key="index"
              :src="img" 
              :preview-src-list="getImageList(detailForm.images)" 
              style="width: 120px; height: 120px; cursor: pointer;" 
              fit="cover">
            </el-image>
          </div>
          <div v-else>-</div>
        </el-descriptions-item>
       
        <el-descriptions-item label="创建时间">{{ (detailForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2" v-if="detailForm.remark">{{ detailForm.remark }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { listDemands, getClaim, delClaim, addClaim, updateClaim } from "@/api/biz/api"
import { listDemands } from "@/api/biz/api"

export default {
  name: "ClaimList",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 诉求表格数据
      claimList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 表单参数
      form: {},
      // 详情表单参数
      detailForm: {},
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        demandsType: null,
        status: null
      },
      // 列信息
      columns: [
        { key: 0, label: `ID`, visible: true },
        { key: 1, label: `企业名称`, visible: true },
        { key: 2, label: `标题`, visible: true },
        { key: 3, label: `内容`, visible: true },
        { key: 4, label: `诉求图片`, visible: true },
        { key: 5, label: `联系人`, visible: true },
        { key: 6, label: `联系电话`, visible: true },
        { key: 7, label: `诉求状态`, visible: true },
        { key: 8, label: `诉求类型`, visible: true }
      ],
      // 表单校验
      rules: {
        companyName: [
          { required: true, message: "企业名称不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        contact: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询诉求列表 */
    getList() {
      this.loading = true
      // 构建符合 API 要求的查询参数
      const params = {
        current: (this.queryParams.current && this.queryParams.current > 0) ? this.queryParams.current - 1 : 0, // API 使用从 0 开始的索引
        size: this.queryParams.size || 10
      }
      if (this.queryParams.demandsType !== null) {
        params.demandsType = this.queryParams.demandsType
      }

      // 只有当 status 有值时才添加
      if (this.queryParams.status !== null) {
        params.status = this.queryParams.status
      }
      
      listDemands(params).then(response => {
        console.log('诉求列表 ：',response);
        
          this.claimList = response.data?.records || []
          this.total = response.data?.total || 0
          this.loading = false
        }
      )
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        companyName: undefined,
        title: undefined,
        content: undefined,
        images: undefined,
        contact: undefined,
        contactPhone: undefined,
        status: "pending",
        appealStatus: "department_processing",
        remark: undefined
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.id)
    //   this.single = selection.length != 1
    //   this.multiple = !selection.length
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加诉求"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getClaim(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改诉求"
      })
    },
    /** 查看详情操作 */
    handleView(row) {
      this.detailForm = { ...row }
      this.detailOpen = true
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateClaim(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addClaim(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除诉求编号为"' + ids + '"的数据项？').then(function() {
        return delClaim(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('claim/list/export', {
        ...this.queryParams
      }, `claim_${new Date().getTime()}.xlsx`)
    },
    // 获取处置状态文本
    getHandlingStatusText(status) {
      const statusMap = {
        'pending': '待处理',
        'first_confirmed': '第一次确认结束',
        'processing': '处理中',
        'completed': '已完成'
      }
      return statusMap[status] || status
    },
    // 获取处置状态类型
    getHandlingStatusType(status) {
      const typeMap = {
        'pending': 'warning',
        'first_confirmed': 'info',
        'processing': 'primary',
        'completed': 'success'
      }
      return typeMap[status] || ''
    },
    // 获取诉求状态文本（根据数字状态）
    getAppealStatusText(status) {
      // 处理数字状态值：-1, 0, 1, 2
      const statusMap = {
        '-1': '审核不通过',
        '0': '待审核',
        '1': '待处理',
        '2': '已完成'
      }
      // 将数字或字符串转换为字符串进行匹配
      const statusKey = status !== null && status !== undefined ? String(status) : ''
      return statusMap[statusKey] || (status !== null && status !== undefined ? String(status) : '-')
    },
    // 获取诉求状态类型（根据数字状态）
    getAppealStatusType(status) {
      // 处理数字状态值：-1, 0, 1, 2
      const typeMap = {
        '-1': 'danger',
        '0': 'warning',
        '1': 'primary',
        '2': 'success'
      }
      // 将数字或字符串转换为字符串进行匹配
      const statusKey = status !== null && status !== undefined ? String(status) : ''
      return typeMap[statusKey] || ''
    },
    // 解析图片字符串为数组
    getImageList(images) {
      if (!images) {
        return []
      }
      // 如果是字符串，按逗号分割并过滤空值
      if (typeof images === 'string') {
        return images.split(',').map(img => img.trim()).filter(img => img.length > 0)
      }
      // 如果已经是数组，直接返回
      if (Array.isArray(images)) {
        return images.filter(img => img && img.length > 0)
      }
      return []
    }
  }
}
</script>
